package cc.ufinity.networkdiagnose.manager;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import cc.ufinity.networkdiagnose.view.R;

public class UpdateVersionManager {
	public static final int UPDATA_CLIENT = 1;
	public static final int GET_UNDATAINFO_ERROR = 2;
	public static final int DOWN_ERROR = 3;

    public static UpdateInfo versioninfo = null;
	private Context ctx;
	private Handler handler;
	
	public UpdateVersionManager(Context ctx, Handler handler) {
		this.ctx = ctx;
		this.handler = handler;
	}
	
	/**
	 * 获取当前程序的版本号 
	 */
	public String getVersionName() throws Exception{
		//获取packagemanager的实例 
		PackageManager packageManager = ctx.getPackageManager();
		//getPackageName()是你当前类的包名，0代表是获取版本信息
		PackageInfo packInfo = packageManager.getPackageInfo(ctx.getPackageName(), 0);
		
	    return packInfo.versionName; 
	}
	
	public UpdateInfo getUpdataInfo(String path) {
		try {
			URL url = new URL(path);
			HttpURLConnection conn =  (HttpURLConnection) url.openConnection(); 
			conn.setConnectTimeout(5000);
			InputStream is =conn.getInputStream(); 
			UpdateInfo info =  UpdataInfoParser.getUpdataInfo(is);  
			versioninfo = info;
			return info;
	
		} catch (Exception e) {
			// 待处理 
			Message msg = new Message();
			msg.what = GET_UNDATAINFO_ERROR;
			handler.sendMessage(msg);
		//	e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 显示是否更新提示对话框
	 */
	public void showUpdataDialog() {
		
		final Dialog waitDialog = new Dialog(ctx, R.style.TRANSDIALOG);
        waitDialog.setContentView(R.layout.updateapk);
        waitDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        waitDialog.setCancelable(false);
        
        //设置窗口里控件的透明度
        Window window = waitDialog.getWindow();
        WindowManager.LayoutParams wl = window.getAttributes();
        wl.flags=WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
        wl.alpha=0.95f;			//０.０全透明．１.０不透明．
        window.setAttributes(wl);

        TextView textView = (TextView)waitDialog.findViewById(R.id.updateinfo);
        TextView textView1 = (TextView)waitDialog.findViewById(R.id.updateInfo1);
        StringBuffer sBuffer = new StringBuffer("更新提示：发现“人人都是测试员”新版本，是否进行版本更新？");
        sBuffer.append("\n\n新版本号：Version ").append(versioninfo.getVersion());
        textView.setText(sBuffer.toString());
        sBuffer =new StringBuffer("版本描述：\n");
        sBuffer.append(versioninfo.getDescription()); 
        textView1.setText(sBuffer.toString());
        Button update = (Button)waitDialog.findViewById(R.id.update);
        Button skip = (Button)waitDialog.findViewById(R.id.skip);
        update.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Message msg = handler.obtainMessage();
				msg.what = UPDATA_CLIENT;
				handler.sendMessage(msg);
				waitDialog.cancel();
			}
		});
        skip.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				waitDialog.cancel();
			}
		});
        
        waitDialog.show();
	}
	
	/**
	 * 从服务器中下载更新APK
	 * @param newUrl
	 */
	public void downLoadApk(final String newUrl) {
		final ProgressDialog pd;	//进度条对话框
		pd = new  ProgressDialog(ctx);
		pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
		pd.setCanceledOnTouchOutside(false);//设置点击进度条以外的地方不消失
		pd.setMessage("正在下载更新");
		pd.show();
		new Thread(){
			@Override
			public void run() {
				try {
					File fileDir = ctx.getFilesDir();
					String localPath = fileDir.getParent() +File.separator;
//					File fileDir =Environment.getExternalStorageDirectory();
//					String localPath = fileDir + File.separator;
					File file0 = new File(localPath);
					if(!file0.exists()) {
						file0.mkdir();
					}
					File file = DownLoadManager.getFileFromServer(newUrl, pd, localPath, ctx);
					//------------------------------------------------ 
					 ZipFile zfile = new ZipFile(file);
			         Enumeration zList = zfile.entries();
			         ZipEntry ze = null;
			         byte[] buf = new byte[1024];
			         while(zList.hasMoreElements()){
			             ze = (ZipEntry)zList.nextElement();    
			             if(!ze.isDirectory() && ze.getName()!=null 
			            		 && (ze.getName().toLowerCase().trim().endsWith(".apk"))){
			                 System.out.println("upZipFile   ze.getName() = " + ze.getName());
			                 String dirstr = localPath + ze.getName();
			                 dirstr.trim();
			                 dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
			                 System.out.println("upZipFile --------> str = " + dirstr);
			                 File f = new File(dirstr);
			                 f.createNewFile();
//			                 continue;
			                 System.out.println("upZipFile --------> ze.getName() = "+ze.getName());
			                 OutputStream os = new BufferedOutputStream(new FileOutputStream(f));
				             InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
				             int readLen=0;
				             while ((readLen=is.read(buf, 0, 1024))!= -1) {
				                 os.write(buf, 0, readLen);
				             }
				             is.close();
				             os.close(); 
				             //给生产的apk文件加上Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE权限，
				             //容许外部其他应用程序调用
				             FileOutputStream fos = ctx.openFileOutput(ze.getName(),
				            		 Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE);  
				             fos.close();
							 sleep(2000);
							 installApk(f);
							 pd.dismiss(); //结束掉进度条对话框   
							 break;
			             }
			         }
			         zfile.close();
					//-------------------------------------------------
//					sleep(3000);
//					installApk(file);
//					pd.dismiss(); //结束掉进度条对话框
				} catch (Exception e) {
					pd.dismiss(); //结束掉进度条对话框
					Message msg = new Message();
					msg.what = DOWN_ERROR;
					handler.sendMessage(msg);
					e.printStackTrace();
				}
			}
		}.start();
	}
	
	
	/**
	 * 安装apk 
	 * @param file
	 */
	private void installApk(File file) {
//		Intent intent = new Intent();
//		//执行动作
//		intent.setAction(Intent.ACTION_VIEW);
//		//执行的数据类型
//		intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive"); 
//		ctx.startActivity(intent);
		String cmd = "chmod 755 " + file;  //755 权限是对apk自身应用具有所有权限， 对组和其他用户具有读和执行权限 
		try {
			Runtime.getRuntime().exec(cmd); 
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		Uri uri = Uri.fromFile(file);
        Intent startIntent = new Intent(Intent.ACTION_VIEW, uri);
        startIntent.setData(uri);
        startIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        startIntent
                .setClassName("com.android.packageinstaller",
                        "com.android.packageinstaller.PackageInstallerActivity");
        ctx.startActivity(startIntent);
	} 
	
	public boolean deleteZIP_APK() {
		File fileDir = ctx.getFilesDir();
		String localPath = fileDir.getParent() +File.separator;
		File file0 = new File(localPath);
		if(!file0.exists()) {
			file0.mkdir();
		}
		System.out.println("------ deleteZIP_APK --------- " + localPath);
		deleteTree(file0, 0);
		return true;
	}

	private static void deleteTree(File f , int n) {
		File childs[] = f.listFiles() ;
		String fileName = "";
		for(int i=0 ; i<childs.length ; i++) {
			if(childs[i].isDirectory()) {
				tree(childs[i] , n+1) ;
			} else {
				fileName = childs[i].getName().toLowerCase().trim();
				if(fileName.endsWith(".apk") || fileName.endsWith(".zip")) {
					childs[i].delete();
				}
			}
		}
	}
	
	public void showTree() {
		File fileDir = ctx.getFilesDir();
		String localPath = fileDir.getParent() +File.separator;
		File file0 = new File(localPath);
		if(!file0.exists()) {
			file0.mkdir();
		}
		System.out.println("------ showTree --------- " + localPath);
		tree(file0, 0);
	}
	
	private static void tree(File f , int n) {
		File childs[] = f.listFiles() ;
		String preStr = new String("") ;
		for(int i=0 ; i<n ; i++) {
			preStr += "== " ;
		}
		for(int i=0 ; i<childs.length ; i++) {
			System.out.println(preStr + childs[i].getName()) ;
			if(childs[i].isDirectory()) {
				tree(childs[i] , n+1) ;
			}
		}
	}
	
}
